package com.example.demo.service.impl;

import com.example.demo.model.TableData;
import com.example.demo.service.TableDataService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class ExcelTableDataService implements TableDataService {

    private static final String FILE_PATH = "src/main/resources/data/products.xlsx";
    private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    @Override
    public List<TableData> getTableData() {
        List<TableData> tableDataList = new ArrayList<>();
        
        try (FileInputStream file = new FileInputStream(new File(FILE_PATH));
             Workbook workbook = new XSSFWorkbook(file)) {

            Sheet sheet = workbook.getSheetAt(0);
            Iterator<Row> rowIterator = sheet.iterator();
            
            // 跳过标题行
            if (rowIterator.hasNext()) {
                rowIterator.next();
            }
            
            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                TableData data = new TableData();
                
                data.setId((long) row.getCell(0).getNumericCellValue());
                data.setName(row.getCell(1).getStringCellValue());
                data.setType(row.getCell(2).getStringCellValue());
                data.setPrice(row.getCell(3).getNumericCellValue());
                
                Cell dateCell = row.getCell(4);
                if (dateCell.getCellType() == CellType.STRING) {
                    data.setDate(LocalDate.parse(dateCell.getStringCellValue(), DATE_FORMAT));
                } else {
                    data.setDate(dateCell.getLocalDateTimeCellValue().toLocalDate());
                }
                
                tableDataList.add(data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        return tableDataList;
    }
}    